// pages/usercenter/exTicket/exTicket.js
import {
  ui
} from '../../../tools/ui'
import {
  ds
} from '../../../tools/data'
import {
  checkTool
} from '../../../tools/check'
import {
  exTool
} from './exTool'
import {
  rsa
} from '../../../tools/rsa'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pickingTime: false,
    values: {},
    action: 'generate',
    ticket: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      ...options
    })
    // console.log(options)
    const titles = {
      generate: '设置水票兑换码参数',
      'exchange': '兑换水票'
    }
    wx.setNavigationBarTitle({
      title: titles[this.data.action],
    })
  },
  async onShow() {
    const {
      action,
      ticketIds
    } = this.data
    // console.log(this.data)
    if (action == 'exchange') {
      const orderRes = ds.coll('orders')
        .where({
          _id: ds.cmd.in(JSON.parse(ticketIds))
        })
        .get()
      const tickets = (await orderRes).data
      // console.log(tickets)
      this.setData({
        tickets
      })
    }
  },
  exchangeTap(e) {
    const {
      ticket
    } = e.currentTarget.dataset
    // console.log(ticket)
    exTool.useTicket(ticket)
      .then(res => {
        this.onShow()
      })
  },
  async generateTap() {
    const {
      values
    } = this.data
    this.checkValues(values)

    ui.loading()
    const user = await new Promise(resolve => {
      ds.cloudGetByOpenid('users', res => {
        resolve(res.result.data[0])
      })
    })
    if (!user) return this.end(false)
    const nickName = user.personInfo?.nickName
    values.owner = {
      id: user._id,
      nickName
    }
    const param = JSON.stringify({
      title: '兑换码',
      nickName
    })
    const ex = rsa.encrypt(JSON.stringify(values))
    this.end(true)
    // console.log(JSON.stringify(values), ex)
    wx.navigateTo({
      url: `/pages/qr/qrcode?param=${param}&ex=${ex}`,
    })
  },
  checkValues(values) {
    checkTool.check([{
      value: values.allowType,
      title: '允许用户',
      fn: v => {
        if (v == '指定用户') return values.userList?.length > 0
        return v
      },
    }, {
      value: values.exOrder,
      title: '优先兑换'
    }, {
      value: '',
      title: '有效期',
      fn: () => {
        if (!values.start && !values.end) return true
        if (values.start && values.end) return values.start <= values.end
        return false
      }
    }])
  },
  onAllowTypeTap() {
    ui.actionSheet(["店员", "指定用户", "仅自己"], (desc, key) => {
      const {
        values
      } = this.data
      values.allowType = desc
      this.setData({
        values
      })
    })
  },
  // 优先兑换
  onExOrderTap() {
    ui.actionSheet(["余票多的", "余票少的", "最新水票", "最旧水票", "兑换人自选"], (desc, key) => {
      const {
        values
      } = this.data
      values.exOrder = desc
      this.setData({
        values
      })
    })
  },
  onStartTimeChange(e) {
    const {
      values
    } = this.data
    const {
      txt,
      timestamp
    } = e.detail
    values.start = timestamp
    this.setData({
      values
    })
  },
  onEndTimeChange(e) {
    const {
      values
    } = this.data
    const {
      txt,
      timestamp
    } = e.detail
    values.end = timestamp
    this.setData({
      values
    })
  },
  onStartTimeCancel() {
    const {
      values
    } = this.data
    values.start = ""
    this.setData({
      values
    })
  },
  onEndTimeCancel() {
    const {
      values
    } = this.data
    values.end = ""
    this.setData({
      values
    })
  },
  selectUserTap() {
    const {
      values
    } = this.data
    const userList = values.userList || []
    const end = (success, msg) => {
      ui.loading(false);
      if (msg) ui.toast(success, msg)
    }
    const that = this
    wx.scanCode({
      onlyFromCamera: true, // 只允许从相机扫码
      async success(res) {
        ui.loading()
        const {
          title,
          ex
        } = JSON.parse(res.result)
        if (title != '我的用户码') return end(false, '错误的用户码')
        // console.log(title, JSON.parse(rsa.decrypt(ex)))
        const {
          userId
        } = JSON.parse(rsa.decrypt(ex)) || {}
        const user = await that.loadUser(userId)
        if (!user) return end(false, '未找到用户')
        if (userList.find(ele => ele.id == userId)) return end(false, '该用户已在允许列表中')
        userList.push({
          id: userId,
          nickName: user.personInfo?.nickName || '(未命名用户)'
        })
        values.userList = userList
        that.setData({
          values
        })
        return end('true')
      },
    })

  },
  loadUser(userId) {
    return new Promise((resolve) => {
      ds.coll('users')
        .where({
          _id: ds.cmd.eq(userId)
        })
        .get()
        .then(res => {
          // console.log(res)
          resolve(res.data[0])
        })
    })
  },
  delUserTap(e) {
    const {
      index
    } = e.currentTarget.dataset
    // console.log(e)
    ui.confirm('确认删除吗？', confirm => {
      if (!confirm) return
      const {
        values
      } = this.data
      const userList = values.userList
      userList.splice(index, 1)
      values.userList = userList
      this.setData({
        values
      })
    })
  },
  onVisibleChange(e) {
    const {
      visible
    } = e.detail
    this.setData({
      pickingTime: visible
    })
  },
  end(success, msg) {
    ui.loading(false)
    if (msg) ui.toast(success, msg)
  }
})